#!/usr/bin/env bash
# Author: jackzang
# mail: jackzang@aishangwei.net
# Date: 2020/2/9

# 如果脚本执行报错，则停止
set -e

# 配置目录
USER_KEYS_DIR=/etc/openvpn/client/keys
EASY_RSA_VER=3
EASY_RSA_DIR=/etc/openvpn/easy-rsa
PKI_DIR=${EASY_RSA_DIR}/${EASY_RSA_VER}/pki

# 安装 zip
rpm -qa|grep ^zip || yum -y install zip

# 循环创建多个用户
cp ./agent_template.ovpn /etc/openvpn/client/
for user in "$@"
do
  # 如果用户已存在，跳出本次循环
  if -d ${USER_KEYS_DIR}/${user} ; then
    echo "[Warning] $user already exists!"
    break
  fi
  # 创建用户
  cd ${EASY_RSA_DIR}/${EASY_RSA_VER}
  ./easyrsa build-client-full ${user} nopass
  mkdir -p ${USER_KEYS_DIR}/${user}
  cp ${PKI_DIR}/ca.crt ${USER_KEYS_DIR}/${user}
  cp ${PKI_DIR}/issued/${user}.crt ${USER_KEYS_DIR}/${user}
  cp ${PKI_DIR}/private/${user}.key ${USER_KEYS_DIR}/${user}
  cp /etc/openvpn/client/agent_template.ovpn ${USER_KEYS_DIR}/${user}/${user}.ovpn
  sed -i 's/user/"${user}"/g' ${USER_KEYS_DIR}/${user}/${user}.ovpn
  cp /etc/openvpn/server/certs/ta.key ${USER_KEYS_DIR}/${user}/ta.key
  # 打包用户文件
  cd ${USER_KEYS_DIR}
  zip -r ${user}.zip ${user}
done
exit 0
